/**
 * @name: 设置水印
 * @param str 水印文字
 * @returns
 */
const genBgSrc = (str: string): string => {
  const can = document.createElement('canvas');
  const isMobile =
    /(iPhone|iPod)/i.test(navigator.userAgent) ||
    /(Android)/i.test(navigator.userAgent);
  const ScreenW = window.innerWidth;
  const ScreenH = window.innerHeight;
  can.width = isMobile ? ScreenW / 3 : 300;
  can.height = isMobile ? ScreenH / 10 : 150;
  const cans = can.getContext('2d');
  if (!cans) return '';
  const dpr = window.devicePixelRatio || 1;
  cans.scale(dpr, dpr);
  cans.fillStyle = 'rgba(200, 200, 200, 0.30)';
  cans.textAlign = 'left';
  cans.textBaseline = 'middle';
  cans.rotate((-30 * Math.PI) / 300);
  if (isMobile) {
    cans.font = `${ScreenW / (10 * 12)}px Vedana`;
  } else {
    cans.font = '10px Vedana';
  }
  cans.fillText(str, 0, can.height / 2);
  return can.toDataURL('image/png');
};

class WaterMark {
  private bgInstance?: HTMLDivElement;

  private static instance?: WaterMark;

  private targetEl = document.body;
  private constructor() {}

  public static getInstance(): WaterMark {
    if (!this.instance) {
      this.instance = new WaterMark();
    }
    return this.instance;
  }

  setTarget(el?: HTMLElement | null) {
    if (!el) return;
    this.targetEl = el;
  }

  setCtx(str: string) {
    const uri = genBgSrc(str);
    if (this.bgInstance) {
      this.bgInstance.style.background = 'url(' + uri + ') left top repeat';
      this.bgInstance.style.width = document.documentElement.clientWidth + 'px';
      this.bgInstance.style.height =
        document.documentElement.clientHeight + 'px';
    } else {
      const div = document.createElement('div');
      div.style.pointerEvents = 'none';
      div.style.top = '0px';
      div.style.left = '0px';
      div.style.position = 'fixed';
      div.style.zIndex = '10000';
      div.style.background = 'url(' + uri + ') left top repeat';
      div.style.backgroundSize = 'auto';
      div.style.width = document.documentElement.clientWidth + 'px';
      div.style.height = document.documentElement.clientHeight + 'px';
      this.bgInstance = div;
      setTimeout(() => {
        this.targetEl.appendChild(div);
        window.addEventListener('resize', () => {
          if (!this.bgInstance) return;
          this.bgInstance.style.width =
            document.documentElement.clientWidth + 'px';
          this.bgInstance.style.height =
            document.documentElement.clientHeight + 'px';
        });
      });
    }
  }

  destroy() {
    const el = this.bgInstance;
    if (el) el.parentNode?.removeChild(el);
  }
}

export default WaterMark.getInstance();
